import React, {
  useState,
  useEffect
} from 'react';
import { withRouter } from 'react-router-dom'
import Zmage from 'react-zmage';
import { Card, Form, Input, Button, Radio, message, Checkbox, Select, InputNumber, Upload } from 'antd';
import BreadcrumbBox from '@/components/Base/BreadcrumbBox';
import { checkRules, useDebounceFn } from '@/utils'
import { PlusOutlined } from '@ant-design/icons';
import { 
  gradeList,
  memberParam,
  memberCreate,
} from '@/api/api'
import './index.scss';

// eslint-disable-next-line no-unused-vars
const Manage = (props) => {
  const breadcrumbList = ['商户管理', '商户开户']
  const [addForm] = Form.useForm();
  const [currencyOptions, setCurrencyOptions] = useState([]);
  const [bankOptions, setBankOptions] = useState([]);
  const [memberTypeOptions, setMemberTypeOptions] = useState([]);
  const [gradeListOptions, setGradeListOptions] = useState([]);
  const [payeeType, setPayeeType] = useState([]);
  
  // 图片
  const [wechatPreviewImage, setWechatPreviewImage] = useState('');
  const [wechatFileList, setWechatFileList] = useState(null)
  const [qqPreviewImage, setQqPreviewImage] = useState('');
  const [qqFileList, setQqFileList] = useState(null)
  const [alipayPreviewImage, setAlipayPreviewImage] = useState('');
  const [alipayFileList, setAlipayFileList] = useState(null)
  
  
  const [data] = useState({
    "wechatFile": "",
    "qqFile": "",
    "alipayFile": "",
    "username": "",
    "userType": "",
    "nickName": "",
    "realName": "",
    "password": "",
    "bankName": "",
    "bankCard": "",
    "bankAccount": "",
    "bankAddress": "",
    "walletAddress": "",
    "payeeType": [],
    "creditGradeId": ""
  })
  // 提交弹框表单做防抖处理
  const submitOk = useDebounceFn((values) => {
    onFinish(values)
  }, 1500, true);
  const getGradeList = async () => {
    try {
      let res = await gradeList()
      if(res.code === 0) {
        let arr = []
        res.data.forEach(item=>{
          arr.push({
            value: item.id,
            label: item.name,
          })
        })
        setGradeListOptions(arr)
      }
    } catch (error) {
      console.log(error)
    }
  }
  const onFinish = async (values) => {
    console.log('Success:', values);
    let formDatas = {}
    for (let key in values) {
      if (values[key]) {
        formDatas[key] = values[key]
      }
    }
    try {
      console.log(formDatas)
      let tMemberCreatedDTO = {
        "username": formDatas.username,
        "userType": formDatas.userType,
        "nickName": formDatas.nickName,
        "realName": formDatas.realName,
        "password": formDatas.password,
        "walletAddress": formDatas.walletAddress,
        "payModelDTO": [],
        "creditGradeId": formDatas.creditGradeId,
      }
      payeeType.forEach(item=>{
        if(item === '3'){
          let payBankModelDTO = {
            "bankName": formDatas.bankName,
            "bankCard": formDatas.bankCard,
            "bankAccount": formDatas.bankAccount,
            "bankAddress": formDatas.bankAddress,
          }
          tMemberCreatedDTO.payBankModelDTO = payBankModelDTO;
        }else if(item === '1'){
          let obj = {
            "payeeType": item,
            "payeeAccount": formDatas.wechat
          }
          tMemberCreatedDTO.payModelDTO.push(obj)
        }else if(item === '2'){
          let obj = {
            "payeeType": item,
            "payeeAccount": formDatas.alipay
          }
          tMemberCreatedDTO.payModelDTO.push(obj)
        }else if(item === '5'){
          let obj = {
            "payeeType": item,
            "payeeAccount": formDatas.qq
          }
          tMemberCreatedDTO.payModelDTO.push(obj)
        }
      })
      var formData = new FormData();
      if(wechatFileList) formData.append('wechatFile',wechatFileList);
      if(alipayFileList) formData.append('qqFile',alipayFileList);
      if(alipayFileList) formData.append('alipayFile',alipayFileList);
      const json = JSON.stringify(tMemberCreatedDTO);
      console.log(json)
      const blob = new Blob([json],{
        type: 'application/json',
      })
      formData.append('tMemberCreatedDTO', blob)
      let res = await memberCreate(formData)
      if (res.code === 0) {
        message.destroy()
        message.success('添加成功')
        addForm.resetFields()
        setPayeeType([])
        setWechatPreviewImage('');
        setWechatFileList(null)
        setQqPreviewImage('');
        setQqFileList(null)
        setAlipayPreviewImage('');
        setAlipayFileList(null)
      }
    } catch (error) {
      console.log(error)
    }
  };
  // 图片上传
  const getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  }
  const wechatHandleChange = async info => {
    if (!info.file.url && !info.file.preview) {
      info.file.preview = await getBase64(info.file.originFileObj, imageUrl => {
        setWechatPreviewImage(imageUrl);
        addForm.setFieldsValue({"wechatFile": imageUrl});
      });
    }else{
      setWechatPreviewImage(info.file.url || info.file.preview);
      addForm.setFieldsValue({"wechatFile": (info.file.url || info.file.preview)});
    }
    setWechatFileList(info.file.originFileObj)
  };
  const qqHandleChange = async info => {
    if (!info.file.url && !info.file.preview) {
      info.file.preview = await getBase64(info.file.originFileObj, imageUrl => {
        setQqPreviewImage(imageUrl);
        addForm.setFieldsValue({"qqFile": imageUrl});
      });
    }else{
      setQqPreviewImage(info.file.url || info.file.preview);
      addForm.setFieldsValue({"qqFile": (info.file.url || info.file.preview)});
    }
    setQqFileList(info.file.originFileObj)
  };
  const alipayHandleChange = async info => {
    if (!info.file.url && !info.file.preview) {
      info.file.preview = await getBase64(info.file.originFileObj, imageUrl => {
        setAlipayPreviewImage(imageUrl);
        addForm.setFieldsValue({"alipayFile": imageUrl});
      });
    }else{
      setAlipayFileList(info.file.url || info.file.preview);
      addForm.setFieldsValue({"alipayFile": (info.file.url || info.file.preview)});
    }
    setAlipayFileList(info.file.originFileObj)
  };
  const uploadButton = (
    <div>
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>上传图片</div>
    </div>
  );
  const memberParamHanlder = async () => {
    try {
      let res = await memberParam()
      if(res.code === 0) {
        if(res.data&&res.data.memberPayeeTypeList){
          let arr = []
          res.data.memberPayeeTypeList.forEach(item=>{
            arr.push({
              value: item.code,
              label: item.name,
            })
          })
          setCurrencyOptions(arr)
        }
        if(res.data&&res.data.bankList){
          let arr = []
          res.data.bankList.forEach(item=>{
            arr.push({
              value: item.name,
              label: item.name, 
            })
          })
          setBankOptions(arr)
        }
        if(res.data&&res.data.memberTypeList){
          let arr = []
          res.data.memberTypeList.forEach(item=>{
            arr.push({
              value: item.code,
              label: item.name,
            })
          })
          setMemberTypeOptions(arr)
        }
      }
    } catch(error) {
      console.log(error)
    }
  }
  
   // 初始化
   useEffect(() => {
    getGradeList()
    memberParamHanlder()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
  return (
    <div className='pass-component'>
      <BreadcrumbBox list={breadcrumbList}></BreadcrumbBox>
      <div className='pass-main'>
        <Card title="添加会员">
          <div className='pass-form'>
              <Form
                name="basic"
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 16 }}
                form={addForm}
                initialValues={data}
                autoComplete="new-password"
                onFinish={submitOk}
              >
                <div className="border1">
                  <Form.Item
                    labelCol={{span: 6}}
                    wrapperCol={{span: 18}}
                    label="会员账号"
                    name="username"
                    rules={[
                      { required: true, message: '请输入会员账号!' },
                    ]}
                  >
                    <Input style={{width:'200px'}} />
                  </Form.Item>
                  <Form.Item
                    labelCol={{span: 6}}
                    wrapperCol={{span: 18}}
                    label="会员类型"
                    name="userType"
                    rules={[
                      { required: true, message: '请选择会员类型' },
                    ]}
                  >
                    <Select style={{width:'200px'}} options={memberTypeOptions} />
                  </Form.Item>
                  <Form.Item
                    labelCol={{span: 6}}
                    wrapperCol={{span: 18}}
                    label="会员昵称"
                    name="nickName"
                    rules={[
                      { required: true, message: '请输入会员昵称!' },
                    ]}
                  >
                    <Input style={{width:'200px'}} />
                  </Form.Item>
                  <Form.Item
                    labelCol={{span: 6}}
                    wrapperCol={{span: 18}}
                    label="真实姓名"
                    name="realName"
                    rules={[
                      { required: true, message: '请输入真实姓名!' },
                    ]}
                  >
                    <Input style={{width:'200px'}} />
                  </Form.Item>
                  <Form.Item
                    labelCol={{span: 6}}
                    wrapperCol={{span: 18}}
                    label="登录密码"
                    name="password"
                    rules={[
                      { required: true, message: '请输入新密码!' },
                      // checkRules('password')
                    ]}
                  >
                    <Input.Password style={{width:'200px'}} />
                  </Form.Item>
                  <Form.Item
                    labelCol={{span: 6}}
                    wrapperCol={{span: 18}}
                    label="信用等级"
                    name="creditGradeId"
                    rules={[
                      { required: true, message: '请选择信用等级' },
                    ]}
                  >
                    <Select style={{width:'200px'}} options={gradeListOptions} />
                  </Form.Item>
                  <Form.Item
                    labelCol={{span: 6}}
                    wrapperCol={{span: 18}}
                    label="收款方式"
                    name="payeeType"
                    rules={[
                      { required: true, message: '请选择收款方式' },
                    ]}
                  >
                    <Select style={{width:'500px'}} onChange={(e)=>{setPayeeType(e)}} mode="multiple" options={currencyOptions} allowClear />
                  </Form.Item>
                </div>
              <div className="bottomModel">
                {
                  payeeType.indexOf('3')!==-1
                  ?
                  <div className="border" >
                    <Form.Item
                      label="银行名称"
                      name="bankName"
                      labelCol={{span: 6}}
                      wrapperCol={{span: 18}}
                      rules={[
                        { required: true, message: '请选择银行名称' },
                      ]}
                    >
                      <Select style={{width:'200px'}} options={bankOptions} />
                    </Form.Item>
                    <Form.Item
                      label="银行卡号"
                      name="bankCard"
                      labelCol={{span: 6}}
                      wrapperCol={{span: 18}}
                      rules={[
                        { required: true, message: '请输入银行卡号!' },
                      ]}
                    >
                      <Input style={{width:'200px'}} />
                    </Form.Item>
                    <Form.Item
                      label="银行姓名"
                      name="bankAccount"
                      labelCol={{span: 6}}
                      wrapperCol={{span: 18}}
                      rules={[
                        { required: true, message: '请输入银行姓名!' },
                      ]}
                    >
                      <Input style={{width:'200px'}} />
                    </Form.Item>
                    <Form.Item
                      label="银行开户地"
                      name="bankAddress"
                      labelCol={{span: 6}}
                      wrapperCol={{span: 18}}
                      rules={[
                        { required: true, message: '请输入银行开户地!' },
                      ]}
                    >
                      <Input style={{width:'200px'}} />
                    </Form.Item>
                  </div>
                  :
                  ''
                }
                {
                  payeeType.indexOf('1')!==-1
                  ?
                  <div className="border">
                    <Form.Item
                      label="微信号"
                      name="wechat"
                      labelCol={{span: 6}}
                      wrapperCol={{span: 18}}
                      rules={[
                        { required: true, message: '请输入微信号!' },
                      ]}
                    >
                      <Input style={{width:'200px'}} />
                    </Form.Item>
                    <Form.Item
                      labelCol={{span: 6}}
                      wrapperCol={{span: 18}}
                      label="收款码"
                      name="wechatFile"
                      rules={[{ required: true, message: '请上传图片' }]}
                    >
                      {
                        wechatPreviewImage
                        ?
                        <Zmage width={102} src={wechatPreviewImage} alt=""/>
                        :
                        ''
                      }
                      <Upload
                        style={{width: '100%', height: '100%'}}
                        name="file"
                        accept="image/png, image/jpeg, image/webp"
                        listType="picture-card"
                        className="avatar-uploader"
                        showUploadList={false}
                        onChange={wechatHandleChange}
                      >
                        {uploadButton}
                      </Upload>
                    </Form.Item>
                  </div>
                  :
                  ''
                }
                {
                  payeeType.indexOf('2')!==-1
                  ?
                  <div className="border">
                    <Form.Item
                      label="支付宝账号"
                      name="alipay"
                      labelCol={{span: 6}}
                      wrapperCol={{span: 18}}
                      rules={[
                        { required: true, message: '请输入微信号!' },
                      ]}
                    >
                      <Input style={{width:'200px'}} />
                    </Form.Item>
                    <Form.Item
                      labelCol={{span: 6}}
                      wrapperCol={{span: 18}}
                      label="收款码"
                      name="alipayFile"
                      rules={[{ required: true, message: '请上传图片' }]}
                    >
                      {
                        alipayPreviewImage
                        ?
                        <Zmage width={102} src={alipayPreviewImage} alt=""/>
                        :
                        ''
                      }
                      <Upload
                        style={{width: '100%', height: '100%'}}
                        name="file"
                        accept="image/png, image/jpeg, image/webp"
                        listType="picture-card"
                        className="avatar-uploader"
                        showUploadList={false}
                        onChange={alipayHandleChange}
                      >
                        {uploadButton}
                      </Upload>
                    </Form.Item>
                  </div>
                  :
                  ''
                }
                {
                  payeeType.indexOf('5')!==-1
                  ?
                  <div className="border">
                    <Form.Item
                      label="QQ号"
                      name="qq"
                      labelCol={{span: 6}}
                      wrapperCol={{span: 18}}
                      rules={[
                        { required: true, message: '请输入QQ号!' },
                      ]}
                    >
                      <Input style={{width:'200px'}} />
                    </Form.Item>
                    <Form.Item
                      labelCol={{span: 6}}
                      wrapperCol={{span: 18}}
                      label="收款码"
                      name="qqFile"
                      rules={[{ required: true, message: '请上传图片' }]}
                    >
                      {
                        qqPreviewImage
                        ?
                        <Zmage width={102} src={qqPreviewImage} alt=""/>
                        :
                        ''
                      }
                      <Upload
                        style={{width: '100%', height: '100%'}}
                        name="file"
                        accept="image/png, image/jpeg, image/webp"
                        listType="picture-card"
                        className="avatar-uploader"
                        showUploadList={false}
                        onChange={qqHandleChange}
                      >
                        {uploadButton}
                      </Upload>
                    </Form.Item>
                  </div>
                  :
                  ''
                }
                {
                  payeeType.indexOf('4')!==-1
                  ?
                  <div className="border">
                    <Form.Item
                      label="钱包编号"
                      name="walletAddress"
                      labelCol={{span: 6}}
                      wrapperCol={{span: 18}}
                      rules={[
                        { required: true, message: '请输入钱包编号!' },
                      ]}
                    >
                      <Input style={{width:'200px'}} />
                    </Form.Item>
                  </div>
                  :
                  ''
                }
              </div>
              <Form.Item wrapperCol={{ offset: 4, span: 16 }}>
                <Button type="primary" htmlType="submit">
                  提交
                </Button>
              </Form.Item>
            </Form>
          </div>
        </Card>
      </div>
    </div>
  )
}
export default withRouter(Manage)